package gold.github.CloudCenter.controller;

import gold.github.CloudCenter.annotation.Authorize;
import gold.github.CloudCenter.model.User;
import gold.github.CloudCenter.model.WeChat.WeChatLoginModel;
import gold.github.CloudCenter.model.WeChat.WeChatResultModel;
import gold.github.CloudCenter.sevice.IUserService;
import gold.github.CloudCenter.utils.JwtUtil;
import gold.github.CloudCenter.utils.RedisUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: XYBH
 * @Description:
 * @Date: Created in 2020/4/23 0023 10:37
 * @Modified:
 */
@RestController
public class AuthController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IUserService userService;

    @PostMapping("api/v1/auth")
    @ApiOperation(value = "微信小程序鉴权接口", notes = "根据json_code进行用户权限鉴定")
    @ApiImplicitParam(name = "code", value = "微信小程序wx.login()所得到的json_code", required = true)
    @ApiResponses({
            @ApiResponse(code = 200, message = "返回token值",examples = @Example(
                    @ExampleProperty(value = "{'token':'ksjdihieiufasn1324r3'}")
            )),
            @ApiResponse(code = 404, message = "用户不存在或不合法")
    })

    public ResponseEntity<Map<String, Object>> auth(@RequestParam("code") String code) {
        Map<String, Object> result = new HashMap<>();
        WeChatLoginModel model = new WeChatLoginModel();
        model.setCode(code);
        WeChatResultModel<User> loginResult = userService.weChatLogin(model);
        User user = loginResult.getUser();
        if (user == null) {
            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        } else {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", user.getUserId());
            claims.put("password", user.getPassword() == null ? user.getOpenId() : user.getPassword());
            claims.put("sessionKey", loginResult.getSessionKey());
            String token = JwtUtil.generate(claims);
            redisUtil.set(user.getUserId(), String.valueOf(user.getAuth()), 0);
            redisUtil.expire(user.getUserId(), 60 * 60 * 24 * 7, 0);
            result.put("token", token);
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
    }

    @GetMapping("api/login")
    @PostMapping("api/login")
    @Authorize
    @ApiOperation(value = "微信模拟登陆接口")
    @ApiResponses({
            @ApiResponse(code = 403, message = "用户权限不足"),
            @ApiResponse(code = 200, message = "返回userId和sessionKey")
    })
    public ResponseEntity<Map<String, Object>> login(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        String sessionKey = (String) request.getAttribute("sessionKey");
        if (StringUtils.isEmpty(userId) && StringUtils.isEmpty(sessionKey)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("sessionKey", sessionKey);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}
